package com.example.springbootlinmtest.config;

/**
 * @author Linm
 * @Date 2023/9/19 20:34
 */

import com.example.springbootlinmtest.mapper.LogConcatMapper;
import com.example.springbootlinmtest.pojo.LogConcat;
import com.example.springbootlinmtest.service.LogConcatService;
import com.example.springbootlinmtest.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Objects;

@Slf4j
@Aspect
@Component
public class LogAspect {
    @Autowired
    private LogService logService;

    @Pointcut("execution(public * com.example.springbootlinmtest.controller.*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

        // 获取真实的IP地址
        String ip = getIpAddr(request);

        // 获取当前登录的用户名
        String username = getUsername();

        // 获取请求的参数
        String params = Arrays.toString(joinPoint.getArgs());

        // 记录下请求内容
        LogConcat logConcat = new LogConcat();
        logConcat.setIp(ip);
        logConcat.setUrl(request.getRequestURL().toString());
        logConcat.setParams(params);
        logConcat.setUsername(username);
        log.info("doBefore==log=={}",logConcat.toString());

        logService.insertLog(logConcat);
        //logRepository.save(log);
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        //LogConcat logConcat = logRepository.findTopByOrderByIdDesc();
        LogConcat logConcat = new LogConcat();
        if (null != ret){
            logConcat.setResult(ret.toString());
            log.info("log==result=={}",logConcat.getResult());
        }

       // logRepository.save(logConcat);
    }

    @AfterThrowing(pointcut = "webLog()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        LogConcat logConcat = new LogConcat(); // logRepository.findTopByOrderByIdDesc();
        logConcat.setException(e.toString());
        log.info("log==exception=={}",logConcat.getException());
        //logRepository.save(log);
    }

    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if(ip.equals("127.0.0.1")){
                // 根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip= inet.getHostAddress();
            }
        }
        if(ip != null && ip.length() > 15){
            if(ip.indexOf(",")>0){
                ip = ip.substring(0,ip.indexOf(","));
            }
        }
        return ip;
    }

    private String getUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            return ((UserDetails)principal).getUsername();
        } else {
            return principal.toString();
        }
    }
}